package com.lagou.filter;

import com.lagou.dubbo.service.IUserService;
import com.lagou.util.HttpResponseStatusUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
@RefreshScope
public class NeedAuthorizeFilter extends HttpResponseStatusUtil implements GlobalFilter, Ordered {

    @Reference
    private IUserService userService;

    @Value("${api.exclude}")
    private String[] excludePaths;

    @Value("${config.cookie.name.token}")
    private String tokenTagName;

    @Value("${config.response.message.unauthorize}")
    private String unauthorizeText;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        for (String exclude : excludePaths) {
            if (path.toLowerCase().startsWith(exclude)) {
                return chain.filter(exchange);
            }
        }

        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        if (!cookies.containsKey(tokenTagName)) {
            return responseStatusAndMessage(response, HttpStatus.UNAUTHORIZED, unauthorizeText);
        }

        String token = cookies.getFirst(tokenTagName).getValue();
        String email = userService.getEmailByToken(token);
        if (email == "") {
            return responseStatusAndMessage(response, HttpStatus.UNAUTHORIZED, unauthorizeText);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
